//商品编辑
const db = uniCloud.database();
const dbJQL = uniCloud.databaseForJQL();
const utils = require('quanzi-utils');
// const cmd = db.command;
module.exports = {
	_before: async function() {
		this.userInfo = await utils.getUsetInfo(this);
	},
	// 新增商品
	async add(data) {
		let uid = await utils.getshopId(this);
		data.money = Number(data.money).toFixed(2) * 100;
		data.deMoney = data.deMoney ? Number(data.deMoney).toFixed(2) * 100 : null;
		data.brandId = uid;
		return await db.collection('mall-goods').add(data);
	},
	//获取商品分类下的商品
	async getList(id) {
		let brand = await dbJQL.collection('mall-brand').doc(id).get();
		let categories = await dbJQL.collection('mall-categories').where({
			user_id: brand.data[0].user_id
		}).field("_id,name").getTemp();
		let goods = await dbJQL.collection('mall-goods').where({
			brandId: id
		}).getTemp();
		let arr = await dbJQL.collection(categories, goods).get();
		console.log('ppp', arr);
		//规定返回格式
		return arr.data.map(i => ({
			name: i.name,
			child: i._id['mall-goods'].map(j => {
				let obj = j;
				delete j.brandId;
				return {
					...obj,
					brandName: brand.data[0].name
				}
			})
		}));
	},
	//获取商品属性
	async deleteList(_id) {
		return db.collection('mall-goods').doc(_id).remove();
	},
	//获取商品属性
	async getEditMsg(id) {
		return db.collection('mall-goods').doc(id).get();
	},
	//修改商品属性
	async updateEdit(id, data) {
		let list = {
			...data
		};
		delete list._id;
		data.money = Number(data.money).toFixed(2) * 100;
		data.deMoney = data.deMoney ? Number(data.deMoney).toFixed(2) * 100 : null;
		return db.collection('mall-goods').doc(id).update(list);
	},
	//获取热门商品
	async getHotGoods() {
		return db.collection('mall-goods').where({
			isHot: true
		}).get();
	},
	async getMyshop() {
		let categories = await dbJQL.collection('mall-categories').where({
			user_id: this.userInfo.uid
		}).field("_id,name").getTemp();
		let goods = await dbJQL.collection('mall-goods').getTemp();
		let arr = await dbJQL.collection(categories, goods).get();
		return arr.data.map(i => ({
			name: i.name,
			child: i._id['mall-goods']
		})).filter(i => i.child.length);
	},
	async getAllGoods(page, limit = 10) {
		let goodsitem = await dbJQL.collection('mall-goods').skip((page - 1) * limit).limit(limit).getTemp();
		let barnditem = await dbJQL.collection('mall-brand').field('_id,name')
			.getTemp();
		return await dbJQL.collection(goodsitem, barnditem).field(
			'_id,name,money,barnditem,thum,brandId').get();
	}
}